package com.example.winner.searchmanager;

import android.support.v7.app.AppCompatActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
 * Created by winner on 2018/6/9.
 */

public class SearchResult extends AppCompatActivity implements OnClickListener{
    private TextView tvquery,tvdata;
    private Button bt;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        tvquery=(TextView)findViewById(R.id.tvquery);
        tvdata=(TextView)findViewById(R.id.tvdata);
        bt=(Button)findViewById(R.id.btnSearch);
        doSearchQuery();
        bt.setOnClickListener(this);
    }
    public void doSearchQuery(){
        final Intent intent = getIntent();
        String query=intent.getStringExtra(SearchManager.QUERY);
        tvquery.setText(query);
        SearchRecentSuggestions suggestions=new SearchRecentSuggestions(
                this, SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE);
        suggestions.saveRecentQuery(query, null);
        if(Intent.ACTION_SEARCH.equals(intent.getAction()))
        {
            Bundle bundle=intent.getBundleExtra(SearchManager.APP_DATA);
            if(bundle!=null){
                String tdata=bundle.getString("data");
                tvdata.setText(tdata);
            }else{
                tvdata.setText("no data");
            }
        }
    }
    @Override
    public void onClick(View v) {
        onSearchRequested();
    }
    @Override
    public boolean onSearchRequested(){
        startSearch("onNewIntent", false, null, false);
        return true;
    }
    /*触发search bar的Activity同时也是处理搜索结果的Activity时，
     * 第一步:在配置文件中，处理搜索结果的Activity添加android:launchMode="singleTop"属性
     * 第二步:重写Activity的onNewIntent(Intent intent)
     */
    @Override
    public void onNewIntent(Intent intent){
        super.onNewIntent(intent);
        String query=intent.getStringExtra(SearchManager.QUERY);
        tvquery.setText(query);
        SearchRecentSuggestions suggestions=new SearchRecentSuggestions(
                this, SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE);
        suggestions.saveRecentQuery(query, null);
        if(Intent.ACTION_SEARCH.equals(intent.getAction())){
            Bundle bundled=intent.getBundleExtra(SearchManager.APP_DATA);
            if(bundled!=null){
                String tdata=bundled.getString("data");
                tvdata.setText(tdata);
            }else{
                tvdata.setText("no data");
            }
        }
    }
}
